import React from 'react';
import { useState } from 'react';
import { Button, message, Popconfirm, Table, Tag, Space } from 'antd';
import { connect } from 'react-redux';
import UserModal from './components/UserModal';

const index = ({ users, dispatch, userListLoading }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [modalRecord, setModalRecord] = useState(undefined);
  const columns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'CreateTime',
      key: 'create_time',
      dataIndex: 'create_time',
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size='middle'>
          <a onClick={() => editModal(record)}>Edit</a>
          <Popconfirm
            title='Are you sure to delete this task?'
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText='Yes'
            cancelText='No'
          >
            <a>Delete</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const confirm = record => {
    const id = record.id;
    dispatch({
      type: 'users/delete',
      payload: {
        id,
      },
    });
  };

  const cancel = e => {
    console.log(e);
  };

  const closeModal = () => {
    setModalVisible(false);
  };
  const editModal = (record) => {
    setModalVisible(true);
    setModalRecord(record);
  };
  const onFinish = (values) => {
    if (modalRecord) {
      const id = modalRecord.id;
      dispatch({
        type: 'users/edit',
        payload: {
          values,
          id,
        },
      });
    } else {
      dispatch({
        type: 'users/add',
        payload: {
          values,
        },
      });
    }
    setModalVisible(false);
  };

  const add = () => {
    setModalVisible(true);
    setModalRecord(undefined);
  };

  return (
    <div>
      <Button type={'primary'} onClick={add}>Add</Button>
      <Table className='list-table' columns={columns} dataSource={users.data} rowKey='id' loading={userListLoading} />
      <UserModal visible={modalVisible} record={modalRecord} closeHandler={closeModal} finish={onFinish} />
    </div>
  );
};

const mapStateToProps = ({ users, dispatch, loading }) => {
  console.log(loading);
  return {
    users, dispatch,
    userListLoading: loading.models.users,
  };
};
export default connect(mapStateToProps)(index);
